package com.qinglei.recoup.longconn.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.longconn.enums.ProtocolVersionEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物联网消息处理
 *
 * @author yujunwei
 * @datetime 2022-03-03 14:35
 */
@Service
@Slf4j
public class IotMessageHandleService {

    @Autowired
    private IotMessageStrategyContext iotMessageStrategyContext;

    public void iotMessageHandle(Map<String, Object> map) {
        String sn = map.get("sn").toString();
        String content = map.get("content").toString();

        JsonNode rootNode = JsonUtils.stringToJson(content);
        if (null == rootNode || null == rootNode.get("items")) {
            log.error("iotMessageHandleService error sn:{}, content:{}", sn, content);
            return;
        }
        JsonNode itemsNode = rootNode.get("items");
        IotMessageStrategyService iotMessageStrategyService = getIotMessageStrategy(itemsNode);
        iotMessageStrategyService.handleMethod(map);
    }

    public IotMessageStrategyService getIotMessageStrategy(JsonNode itemsNode) {
        List<ProtocolVersionEnum> protocolVersionList = Arrays.asList(ProtocolVersionEnum.values()).stream().filter(protocolVersion -> StringUtils.isNotBlank((protocolVersion.getKey()))).collect(Collectors.toList());
        for (ProtocolVersionEnum protocolVersion : protocolVersionList) {
            JsonNode protocolNode = itemsNode.get(protocolVersion.getKey());
            if (null != protocolNode)
                return iotMessageStrategyContext.getIotMessageStrategy(protocolVersion.getVersion());
            continue;
        }
        return iotMessageStrategyContext.getIotMessageStrategy(ProtocolVersionEnum.DEFAULT.getVersion());
    }

}
